<?php

Loader::loadClass('SecurityUtilEx', "modules/IShopStore/pnincludes");

/**
* //////////////////////////////////////////////////
* auto execute , for initialize config variable
* this function auto call every page has been fetch
*/
function _autoexecute(){

}

function IShopStore_user_permission()
{
  // Security check
  //we are allow for admin access level , see in config.php variable name ACCESS_EDIT
  if (!SecurityUtil::checkPermission('IShopStore::', '::', ACCESS_COMMENT)) {
      LogUtil::registerPermissionError(pnModUrl('Users','user','loginscreen'));
  }
}

/**
* smarty template auto call before render
*/
function _preRender(&$render){
  $lang    = FormUtil::getPassedValue ('lang', false , 'GET');
  $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');

  $render->assign ('_GET', $_GET);
  $render->assign ('_POST', $_POST);
  $render->assign ('_REQUEST', $_REQUEST);

  $render->assign('ctrl', $ctrl);
  //$render->assign('setting',InnoUtil::getSetting());
  $render->assign('user',   InnoUtil::getUserInfo());

  if ($lang){
    $render->assign('lang', $lang);
  }else{
    $render->assign('lang', pnUserGetLang());
  }
  $render->assign('access_edit', SecurityUtil::checkPermission('IShopStore::', '::', ACCESS_COMMENT));
}

/**
 * Main user function . the user side page controller
 * @author Chayakon PONGSIRI
 * @return string HTML string
 */
function IShopStore_user_main() {
    //_autoexecute();
    //return IShopStore_user_list();
    return IShopStore_user_ajax();
    
}

/**
* display page with out class loader
*/
function IShopStore_user_page() {
    //_autoexecute();
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', 'home' , 'GET');
    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'page' , 'GET');
    $render = pnRender::getInstance('IShopStore');
    
    _preRender($render);
    //try to load class
    $class = Loader::loadClassFromModule ('IShopStore','User' . $ctrl, false);
    if ($class){
      $object  = new $class ();
      if (method_exists($object,'selectExtendResult')){
        $resultex = $object->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
    }

    return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');

}

/**
* display page with class that extend Object 
*/
function IShopStore_user_view() {
    //_autoexecute();
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'view' , 'GET');
    //$id the id no if edit form
    $id      = FormUtil::getPassedValue ('id', null , 'GET');
    //pagnigation variable
    $filter  = FormUtil::getPassedValue ('filter', 0);
    $offset  = FormUtil::getPassedValue ('startnum', 0);
    $sort    = FormUtil::getPassedValue ('sort', '');
    $where   = '';

    $pagesize = pnModGetVar ('IShopStore', 'pagesize') ? pnModGetVar ('IShopStore', 'pagesize') : 10;
    $render = pnRender::getInstance('IShopStore');
    
    if ($id){
      //load class
      if (!($class = Loader::loadClassFromModule ('IShopStore',$ctrl, false)))
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");

      $object  = new $class ();
      $object->get($id);
      if (method_exists($object,'genFilter')){
        $where = $object->genFilter();
      }
      if (method_exists($object,'selectExtendResult')){
        $resultex = $object->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      $render->assign ('view', $object->_objData);
    }
    _preRender($render);
    return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');
}

/**
* display page with class that extend Object Array
*/
function IShopStore_user_list() {
    //_autoexecute();
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', 'Item' , 'GET');
    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'list' , 'GET');
    $method  = FormUtil::getPassedValue ('method', '' , 'GET');
    //$keyword = FormUtil::getPassedValue ('keyword', '' , 'GET');
    $categories_id = FormUtil::getPassedValue ('categories_id', '' , 'GET');
//echo "cat ".$categories_id; exit;
    if($func == '' || $func == 'main'){
      $func  = 'list';
    }
    $is_export = false;
    //pagnigation variable
    $filter  = FormUtil::getPassedValue ('filter', 0);
    //echo $filter; exit;
    $offset  = FormUtil::getPassedValue ('startnum', 0);
    $sort    = FormUtil::getPassedValue ('sort', '');

    /*
    else if ($ctrl=='categories'){
        $pagesize = pnModGetVar ('IShopStore', 'pagesize') ? pnModGetVar ('IShopStore', 'pagesize') : 20;
    }
    */
    if($filte) {
        $pagesize = pnModGetVar ('IShopStore', 'pagesize') ? pnModGetVar ('IShopStore', 'pagesize') : 15;
    }

    $render = pnRender::getInstance('IShopStore');

    //check is export
    $export = FormUtil::getPassedValue ('export', false);
    $button_export = FormUtil::getPassedValue ('button_export', false);
    $button_export_x = FormUtil::getPassedValue ('button_export_x', false);
    if ($export || $button_export || $button_export_x){
      $is_export = true;
    }
    if (!($class = Loader::loadClassFromModule ('IShopStore',$ctrl, true)))
      return LogUtil::registerError ("Unable to load class [$ctrl] ...");

    $objectArray = new $class ();
    $where   = null;
    $sort = null;
    if (method_exists($objectArray,'genFilter')){
      $where = $objectArray->genFilter();
    }
    if (method_exists($objectArray,'genSort')){
      $sort = $objectArray->genSort();
    }
    if (method_exists($objectArray,'selectExtendResult')){
      $resultex = $objectArray->selectExtendResult();
      $render->assign('extendResult', $resultex);
    }
    if (empty($where)){
      $where = implode(' AND ',$objectArray->_objWhere);
    }else if (is_array($objectArray->_objWhere)){
      $where .= implode(' AND ',$objectArray->_objWhere);
    }else if (!empty($objectArray->_objWhere)){
      $where .= ' AND ' . $objectArray->_objWhere;
    }
    if (empty($sort)){
      $sort = $objectArray->_objSort;
    }

    //Spilt page
    $pager = array();
    $pager['numitems']     = $objectArray->getCount($where , true);
    $pager['itemsperpage'] = $pagesize;
    $render->assign ('startnum', $offset);
    $render->assign ('pager', $pager);
    $objectArray->get ($where, $sort , $offset, $pagesize);

    //assign to view
    
    //var_dump($objectArray); exit;
    $render->assign('objectArray', $objectArray->_objData);

    _preRender($render);

    return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');

}

function IShopStore_user_form() {
    //IShopStore_user_permission();
    //$uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
    //$user    = InnoUtil::getUserInfo();
    //if ( $id && ((($uid == $user['uid']) && ($uid != '') && $uid ) || (intval($user['level']) == intval(constant('ADMIN_EDIT_LEVEL')) )) ) {
      //$ctrl the class name
      $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
      //$method the method of request for edit or view enum[ view | form | delete | list | page]
      $func  = FormUtil::getPassedValue ('func', 'form' , 'GET');
      //$id the id no if edit form
      $id      = FormUtil::getPassedValue ('id', null , 'GET');
      //pagnigation variable
      $filter  = FormUtil::getPassedValue ('filter', 0);
      $offset  = FormUtil::getPassedValue ('startnum', 0);
      $sort    = FormUtil::getPassedValue ('sort', '');
      $where   = '';

      $pagesize = pnModGetVar ('IShopStore', 'pagesize') ? pnModGetVar ('IShopStore', 'pagesize') : 100;
      $render = pnRender::getInstance('IShopStore');
      $mode = null;

      //load class
      if (!($class = Loader::loadClassFromModule ('IShopStore',ucfirst($ctrl), false)))
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");

      $object  = new $class ();

      if (!SecurityUtilEx::checkPermissionFromObject($object)){
        return LogUtil::registerError ("ʨǹ�թ�١�ӡѴ㋩㪩䴩੾ҐʁҪԡ෨ҹѩ�");
      }
      if (method_exists($object,'genPermission')){
        $permit = $object->genPermission();
        if (empty($permit)){
          return LogUtil::registerError ("ʨǹ�թ�١�ӡѴ㋩㪩䴩੾ҐʁҪԡ෨ҹѩ�");
        }
      }
      if ($id && $object){

        $object->get($id);

        $mode = 'edit';  
        $render->assign ('form', $object->_objData);
        
      }else{
        $mode = 'new';
      }
      $render->assign ('mode', $mode);
      
      if (method_exists($object,'selectExtendResult')){
        $resultex = $object->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      _preRender($render);
      return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');
    //}
}

/**
* for delete object for database by specify id
*/
function IShopStore_user_delete() {
    //IShopStore_user_permission();
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
    $id      = FormUtil::getPassedValue ('id', false , 'GET');
    $forward = FormUtil::getPassedValue ('forward', false , 'GET');

    $uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
    $user    = InnoUtil::getUserInfo();

      //load class
      if (!($class = Loader::loadClassFromModule ('IShopStore', ucfirst($ctrl), false)))
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");

      $object  = new $class ();
      $object->_objData[$object->_objField] = $id;
      //var_dump($object); exit;
      $object->delete ();
      

      if (method_exists($object,'genForward')){
        $forward_url = $object->genForward();
      }else if (!is_array($forward) && $forward){
        $forward_url =  str_replace("&amp;", "&", $forward);
      }else if (is_array($forward)){
        $forward_url = InnoUtil::createUrlFromArray($forward);
      }else{
        $forward_url = pnModURL('IShopStore', 'user', 'list' , array('ctrl'=>$ctrl));
      }
      pnRedirect($forward_url);
      die;

}

/**
* for set/unset status for hot package
* ex. index.php?module=IShopStore&func=status&ctrl=Tour&id=XXX&status=YYYY
*/
function IShopStore_user_status() {
    IShopStore_user_permission();
  //get status from url 
  $id        = FormUtil::getPassedValue ('id', false , 'GET');
  $status    = FormUtil::getPassedValue ('status', false , 'GET');
  $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');

  if ($status && $id){
    //set status
    $where  = " itm_id = ".$id;

    $objects = array(
                    'recommend'        => $status
                   );

      DBUtil::updateObject($objects,'ishopstore_item', $where);
  }
  $list_url = pnModURL('IShopStore', 'user', 'list' , array('ctrl'=>$ctrl));
  pnRedirect($list_url);
  die;
}

/**
* this function is for compute order and do something about its
*
*/
function IShopStore_user_checkout()
{  
  if(!SessionUtil::getVar('_CART')&&!SessionUtil::getVar('_CART_CONF'))
  {
    return LogUtil::registerError(__('Error! Cart is empty.'), NULL, NULL, array('confirmtou' => 0, 'returnpage' => 'index.php'));
  }
  
  $action        = FormUtil::getPassedValue ('action', "detailPage" , 'GET');
  $render = pnRender::getInstance('IShopStore');
  

  
  $render->assign("action",$action);
  
  switch($action)
  {
    case "detailPage" :
        if(SessionUtil::getVar('_CART'))
        {
          if (!($class = Loader::loadClassFromModule ('IShopStore',ucfirst("Item"), false))){
            return LogUtil::registerError ("Unable to load class [Item] ...");
          }
          $object  = new $class ();
          
          $items = SessionUtil::getVar('_CART');
          $i=0;
          foreach($items AS $key=>$value){
            $object->get($key);
            $itemLists[$i] = $object->getData();
            $itemLists[$i][amount] = $value[amount];
            $i++;
          }
          //var_dump($itemList);exit;
          $render->assign("itemLists",$itemLists);
          SessionUtil::setVar('_CART_CONF',$itemLists);
          $render->assign("nextURL",pnModURL("IShopStore","user","checkout",array("action"=>"formPage")));
        }else{
          $render->assign("itemLists",FALSE);
        }
        return $render->fetch('user_page_checkout.htm');
        break;
    case "formPage" :
        SessionUtil::delVar('_CART');
        return $render->fetch('user_page_checkout.htm');
        break;
    case "completed" :
    
        if (!($class = Loader::loadClassFromModule ('IShopStore',ucfirst("Order"), false))){
            return LogUtil::registerError ("Unable to load class [Order] ...");
          }
        $orderObject  = new $class ();
        $orderObject->getDataFromInput('form',null,'POST');
        
        $form = FormUtil::getPassedValue ('form',null,'POST');
        
        if ($_POST['button_delete'] || $_POST['button_delete_x']){
          $orderObject->delete ();
        } else{
          $orderObject->save ();
          $forward[status] = "success";
        }
        
        $insertedID = $orderObject->getID();
        
        $items = SessionUtil::getVar('_CART_CONF');
        $i=0;
        foreach($items AS $item){
          $itemLists[$i][item_id] = $item[id];
          $itemLists[$i][order_id] = $insertedID;
          $itemLists[$i][quantity] = $item[amount];
          $i++;
        }
        
        if(DBUtil::insertObjectArray($itemLists,"ishopstore_order_item"))
        {
          $render->assign("form",$form);
          $emailTemplate = $render->fetch('_email_template.htm');
          $isComplete = TRUE;
          $render->assign("isComplete",$isComplete);
          pnMail($form[email],"Order Confirmation",$emailTemplate,NULL,TRUE);
        }else{
          $render->assign("form",FALSE);
          $isComplete = FALSE;
          $render->assign("isComplete",$isComplete);
        }
        
        return $render->fetch('user_page_checkout.htm');
        break;
    default:
        break;
  }
  
}

function IShopStore_user_ajax(){
    $ctrl    = FormUtil::getPassedValue ('ctrl', 'ScrollItems' , 'GET');    
    $render = pnRender::getInstance('IShopStore');
    
    return $render->fetch('user_ajax_'.strtolower($ctrl).'.htm');
}

